package com.rabbitmq.demo.producer;

import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.TimeoutException;

/**
 * @author Lenovo-LQ
 */
public class RabbitMQDirectExchangeProducer {
    private static String host = "127.0.0.1";
    private static String userName = "guest";
    private static String passWord = "guest";
    private static int port = 5672;
    /**
     * @param args
     */
    public static void main(String[] args) {

        try {
            //1、连接到RabbitMQ服务器
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(host);
            factory.setPort(port);
            factory.setUsername(userName);
            factory.setPassword(passWord);
            Connection connect = factory.newConnection();
            //并发channel多路复用connect
            createMultiChannel(connect);
            Channel channel = connect.createChannel();
            //2、指定要发送消息到哪个队列
            AMQP.Queue.DeclareOk declareOK = channel.queueDeclare("test", false, false, false, null);
            //3、指定消息交换机，路由关键字,附加属性和要发送的消息(exchange空字符为默认的direct交换器)
            channel.basicPublish("", "test", null, "hello rabbit".getBytes("UTF-8"));
            channel.close();
            connect.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 并发channel多路复用connect
     * @param connect1
     */
    private static void createMultiChannel(Connection connect1){
        final Connection connect = connect1;
        int i = 0;
        while (i <10)
        {
            new Thread(new Runnable() {
                public void run() {
                    Channel channel = null;
                    try {
                        if(connect.isOpen()) {
                            channel = connect.createChannel();
                            AMQP.Queue.DeclareOk declareOK = channel.queueDeclare("test", false, false, false, null);
                            channel.basicPublish("", "test", null, "hello rabbit".getBytes("UTF-8"));
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                    }
                }
            }).start();
            i++;
        }
    }


}
